import { defineStore } from "pinia";
import { ref } from "vue";
import type {
  LcdItem,
  StatusBarItem,
  StateChangeItem,
  ChannelItem,
  ChannelSimpleItem,
  HjumperItem,
} from "@/api/hmi/home.api";
import { HMI_HOME_API } from "@/api/hmi/home.api";

/**
 * 首页大屏数据 Store
 * - 仅封装 API 调用，采用 new Promise 风格
 * - 由 View 持有本地状态，View 外层 try-catch 捕获错误
 */
export const useHomeStore = defineStore("home", () => {
  const loading = ref(false);
  const error = ref<string | null>(null);

  const fetchLcd = (): Promise<LcdItem[] | null> => {
    loading.value = true;
    error.value = null;
    return new Promise((resolve) => {
      HMI_HOME_API.fetchLcd()
        .then((res) => resolve(res))
        .catch((err: any) => {
          console.error("fetchLcd error", err);
          error.value = err?.message || "获取 LCD 数据失败";
          resolve(null);
        })
        .finally(() => (loading.value = false));
    });
  };

  const fetchStatusBar = (cpu: number = 1): Promise<StatusBarItem[] | null> => {
    loading.value = true;
    error.value = null;
    return new Promise((resolve) => {
      HMI_HOME_API.fetchStatusBar(cpu)
        .then((res) => resolve(res))
        .catch((err: any) => {
          console.error("fetchStatusBar error", err);
          error.value = err?.message || "获取状态栏数据失败";
          resolve(null);
        })
        .finally(() => (loading.value = false));
    });
  };

  const fetchStateChange = (cpu: number = 1): Promise<StateChangeItem[] | null> => {
    loading.value = true;
    error.value = null;
    return new Promise((resolve) => {
      HMI_HOME_API.fetchStateChange(cpu)
        .then((res) => resolve(res))
        .catch((err: any) => {
          console.error("fetchStateChange error", err);
          error.value = err?.message || "获取变位信息失败";
          resolve(null);
        })
        .finally(() => (loading.value = false));
    });
  };

  const fetchChannels = (cpu: number = 1): Promise<ChannelItem[] | null> => {
    loading.value = true;
    error.value = null;
    return new Promise((resolve) => {
      HMI_HOME_API.fetchChannels(cpu)
        .then((res) => resolve(res))
        .catch((err: any) => {
          console.error("fetchChannels error", err);
          error.value = err?.message || "获取通道值失败";
          resolve(null);
        })
        .finally(() => (loading.value = false));
    });
  };

  const fetchHjumpers = (cpu: number = 1): Promise<HjumperItem[] | null> => {
    loading.value = true;
    error.value = null;
    return new Promise((resolve) => {
      HMI_HOME_API.fetchHjumpers(cpu)
        .then((res) => resolve(res))
        .catch((err: any) => {
          console.error("fetchHjumpers error", err);
          error.value = err?.message || "获取硬压板信息失败";
          resolve(null);
        })
        .finally(() => (loading.value = false));
    });
  };

  /**
   * 将完整的通道值数组映射为精简视图（仅保留 序号/名称/量值）
   */
  const toChannelSimple = (items: ChannelItem[] = []): ChannelSimpleItem[] => {
    // 近零抖动过滤：abs(value) < 0.004 视作 0
    const EPS = 0.004;
    const normalize = (n: number) => {
      const v = Number(n) || 0;
      return Math.abs(v) < EPS ? 0 : v;
    };
    return items.map((it) => ({ 序号: it.序号, 名称: it.名称, 量值: normalize(it.量值) }));
  };

  const resetState = () => {
    loading.value = false;
    error.value = null;
  };

  return {
    loading,
    error,
    fetchLcd,
    fetchStatusBar,
    fetchStateChange,
    fetchChannels,
    fetchHjumpers,
    toChannelSimple,
    resetState,
  };
});

export const useHomeStoreHook = () => useHomeStore();

